<?php
namespace frontend\models;

use Yii;
use yii\base\Model;
use common\models\User;

/**
 * Signup form
 * 注册表单验证
 */
class SignupForm extends Model
{
    public $mobile;
    public $email;
    public $username;
    public $password;
    public $password2;
    public $insertUid = 0 ;

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['mobile','username'], 'trim'],
            ['mobile', 'required','message' => '手机号不能为空'],
            ['mobile', 'unique', 'targetClass' => '\common\models\User', 'message' => '该手机号账号已存在'],
            ['mobile','match','pattern'=>'/^1[0-9]{10}$/','message'=>'{attribute}必须为1开头的11位纯数字'],
            ['password', 'required','message' => '密码不能为空'],
            ['password2', 'required','message' => '重复密码不能为空'],
            [['password','password2'], 'string','min'=>6, 'max' => 16,'message'=>'{attribute}位数为6至16位'],
            ['password2','compare','compareAttribute'=>'password','message'=>'两次密码不一致'],
        ];
    }

    /**
     * Signs user up.
     *
     * @return bool whether the creating new account was successful and email was sent
     */
    public function signup()
    {
        if (!$this->validate()) {
            return null;
        }
        $user = new User();
        $user->mobile = $this->mobile;
        $user->username = $this->username;
        $user->setPassword($this->password);
        $user->generateAuthKey();
        $user->generateEmailVerificationToken();
        $result = $user->save();
        $this->insertUid = $user->getId();
        return $result ;
    }

    /**
     * Sends confirmation email to user
     * @param User $user user model to with email should be send
     * @return bool whether the email was sent
     */
    protected function sendEmail($user)
    {
        return Yii::$app
            ->mailer
            ->compose(
                ['html' => 'emailVerify-html', 'text' => 'emailVerify-text'],
                ['user' => $user]
            )
            ->setFrom([Yii::$app->params['supportEmail'] => Yii::$app->name . ' robot'])
            ->setTo($this->email)
            ->setSubject('Account registration at ' . Yii::$app->name)
            ->send();
    }
}
